<!-- 一些名词概念备注 -->
<!-- 原始分配合同额: 其实说的就是 合同分配额(元) model.contractAmount -->
<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!-- 基本信息 -->

        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle" >
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="单据编号">
              <a-input placeholder="请输入单据编号" v-model="model.billNo" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <select-user-by-dep :multi="false" v-model="model.handlerId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
              <j-select-depart v-model="model.handlerDeptId" disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="项目信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-distribution-input
                    :disabled="formDisabled"
                    projectStatus="2"
                    :proDisabled="true"
                    :isContractManager="true"
                    v-model="model.projectId"
                    placeholder="请选择项目名称"
                    @input="onChangeProjectName"></select-project-distribution-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
                  <a-input disabled v-model="model.finalNo" placeholder="请输入项目编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
                  <select-team-input
                    disabled
                    v-model="model.teamName"
                    :tdlx="1"/>

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
                  <select-user-by-dep disabled v-model="model.undertaker" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="立项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectEstablishDate">
                  <j-date
                    disabled
                    placeholder="请选择立项日期"
                    v-model="model.projectEstablishDate"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
                  <select-Company-input placeholder="请输入签订单位" disabled v-model="model.signUnit"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.year"
                    dictCode="yjgsnd"
                    placeholder="请选择业绩归属年度"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
                  <select-customer-input
                    disabled
                    v-model="model.ownerUnit"
                    commercialType="1"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contacts">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.contacts"
                    :dictCode="cust_lxr"
                    placeholder="请选择联系人"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactTel">
                  <a-input disabled v-model="model.contactTel" placeholder="请输入联系电话"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" >
                <a-form-model-item prop="areaCode" label="项目所在地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <AddressChoice disabled type="cascader" v-model="model.areaCode" placeholder="请输入省市区" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="projectAddress" label="项目详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-model="model.projectAddress" placeholder="请输入项目详细地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectSource">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.projectSource"
                    dictCode="xmly_type"
                    placeholder="请选择项目来源"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedContractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.estimatedContractAmount"
                    placeholder="请输入预计合同额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedContractcapitalChineseAmount">
                  <a-input disabled v-model="model.estimatedContractcapitalChineseAmount" placeholder="请输入预计合同额大写"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="立项事由及说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="establishReason">
                  <a-textarea :max-length="500" disabled v-model="model.establishReason" rows="4" placeholder="请输入立项事由及说明"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="项目附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload v-if="!formDisabled" disabled v-model="model.attachment"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.attachment)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="需分配任务信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <!-- @back="changeTask" -->
                <a-form-model-item label="任务编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskId">
                  <SelectTaskFileInput
                    :disabled="formDisabled"
                    v-model="model.taskId"
                    :projectId="model.projectId"
                    customDistributionType="producting,finish"
                    @input="onTaskIdInput"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">
                  <a-input
                    disabled
                    v-model="model.categoryName"
                    placeholder="请选择业务分类" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同占比(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractRate"
                    placeholder="请输入合同占比"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同分配额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractAmount"
                    placeholder="请输入合同分配额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col  :span="8">
                <a-form-model-item label="切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutContractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.cutContractAmount"
                    placeholder="请输入切割合同额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
                  <select-team-input
                    @back="changeVal"
                    disabled
                    v-model="model.productTeam"
                    :tdlx="2"
                    :triggerChange="true"/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="生产公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productCompanyId">
              <select-Company-input :disabled="formDisabled" placeholder="请选择生产公司" v-model="model.productCompanyId" disabled />
                 </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="需分配合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="separateContractAmount">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.separateContractAmount"
                    placeholder="请输入需分配合同额"
                    style="width: 100%"
                    @blur="handleChangeSeparateContractAmount"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="需分配切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="needCutContractAmount">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.needCutContractAmount"
                    placeholder="请输入需分配切割合同额"
                    style="width: 100%"
                    @blur="handleChangeSeparateContractAmount"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否作废" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCancel">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isCancel"
                    dictCode="YES_OR_NO"
                    placeholder="请选择是否作废"
                    triggerChange
                    @change="handleChangeIsCancel"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reason">
                  <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.reason" rows="4" placeholder="请输入说明"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="file">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.file"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.file)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="新增分配任务信息">
            <a-row :gutter="48">
              <a-col :span="24" >
                <div style="margin-bottom: 6px;margin-top: 6px" >
                  <a-button @click="handleMemberAdd" v-if="!formDisabled" type="primary">新增</a-button>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  bordered
                  :components="draggableComponent"
                  :loading="memberLoading"
                  :columns="memberColumns"
                  :pagination="false"
                  :data-source="model.redistributionDtList"
                  :scroll="{x: scrollX}"
                >
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleMemberEdit(record)"/>
                      <a-divider type="vertical"/>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleMemberDelete(record.id)">
                        <a-button
                          class="ruleButton"
                          :ghost="true"
                          type="primary"
                          icon="delete"
                        />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="需分配款项信息">
            <a-row :gutter="48">
              <a-col :span="24" >
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="index"
                  bordered
                  :components="draggableComponent"
                  :loading="receivablePaymentLoading"
                  :columns="receivablePaymentColumns"
                  :pagination="false"
                  :data-source="receivablePaymentList"
                  :scroll="{ x: scrollX }"
                >
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled && record.shouldPayFlag != '1'">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handlePaymentEdit(record)"/>
                    </template>
                    <template v-else>
                      <a @click="handleDetail(record)">查看</a>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpMyOmcTaskPaymentModal ref="paymentForm" @ok="memberModalFormOk" :templateDataList="templateDataList" ></ErpMyOmcTaskPaymentModal>
    <ErpOmcTaskRedistributionFormPrint id="taskContent" v-if="formBpm" class="print_style" :formData="model" :formDataHistory="formData"></ErpOmcTaskRedistributionFormPrint>
    <ErpOmcTaskRedistributionMemberModal
      ref="memberList"
      :estimatedContractAmount="model.estimatedContractAmount"
      :separateContractAmount="model.separateContractAmount"
      @ok="submitCallback" />
    <ErpOmcTaskRedistributionPaymentModal
      ref="paymentModal"
      :estimatedContractAmount="model.estimatedContractAmount"
      :separateContractAmount="model.separateContractAmount"
      :redistributionDtList="paymentTaskList"
      :projectId="model.projectId"
      @ok="submitPaymentModal" />
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { TaskRedistribution } from '../mixins/TaskRedistribution'
import {
  filterMultiDictText,
  initDictOptions
} from '@/components/dict/JDictSelectUtil'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import AddressChoice from '@/components/AddressChoice/AddressChoice';
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpOmcTaskRedistributionFormPrint from './ErpOmcTaskRedistributionFormPrint' // 打印
import SelectProjectDistributionInput from '@/views/scy/components/SelectProjectDistributionInput'; //  项目名称
import SelectTaskFileInput from '@/views/scy/components/SelectTaskFileInput'; //  任务编号
import SelectProcessTemplateInput from '@/views/scy/components/SelectProcessTemplateInput' // 进度模板
import ErpMyOmcTaskPaymentModal from './reference/ErpMyOmcTaskPaymentModal' // 款项计划
import ErpOmcTaskRedistributionMemberModal from './reference/ErpOmcTaskRedistributionMemberModal' // 新增分配任务信息
import ErpOmcTaskRedistributionPaymentModal from './reference/ErpOmcTaskRedistributionPaymentModal' // 需分配款项信息
import Decimal from 'decimal.js'
import { DragResizable } from '@/mixins/DragResizable'
export default {
  name: 'ErpOmcTaskRedistributionForm',
  mixins: [DisabledAuthFilterMixin, viewFile, DragResizable, TaskRedistribution],
  components: {
    ViewFileModal,
    SelectUserByDep,
    SelectTeamInput,
    SelectCustomerInput,
    AddressChoice,
    SelectCompanyInput,
    CommonFlowList,
    ErpOmcTaskRedistributionFormPrint,
    SelectProjectDistributionInput, //  项目名称
    SelectTaskFileInput, // 任务编号
    SelectProcessTemplateInput, // 进度模板
    ErpMyOmcTaskPaymentModal,
    ErpOmcTaskRedistributionMemberModal,
    ErpOmcTaskRedistributionPaymentModal
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    taskId: {
      type: String,
      default: '',
      required: false
    },
    projectNameId: {
      type: String,
      default: '',
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    isShowCutContractAmount:{
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      paymentTaskList: [], // 任务委托数据
      taskInfoObj: { id: '' },
      originalContractAmount: 0, // 原合同分配额
      cutTheContractAmount:0, // 原切割合同额
      memberLoading: false,
      activeKey: ['1', '2', '3', '4', '5', '6'],
      tableNoData: { emptyText: () => (
        <a-empty description="合同未签订，暂无数据" />
      ) },
      templateLoading: false,
      progressNodeVoLoading: false,

      model: {
        taskId: null,
        isCancel: null,
        attachment: null,
        file: null,
        redistributionDtList: [],
        dataSource: [],
        handlerId: undefined,
        handlerDeptId: undefined,
        createTime: undefined,
        undertaker: undefined,
        projectId: undefined
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      templateDataList: [], // 进度模板列表
      progressNodeVoList: [], // 款项进度列表
      confirmLoading: false,
      validatorRules: {
        projectId: [
          { required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }
        ],
        separateContractAmount: [
          { required: true, message: '请输入需分配合同额!' }
        ],
        needCutContractAmount: [
          { required: true, message: '请输入需分配切割合同额!' }
        ],
        // cutContractAmount: [
        //   { required: true, message: '请输入切割合同额!' }
        // ],
        isCancel: [
          { required: true, message: '请选择是否作废!' }
        ],
        taskId: [
          { required: true, message: '请选择任务编号!' }
        ]
      },
      url: {
        add: '/api/erp/task/erpOmcTaskRedistribution/add',
        edit: '/api/erp/task/erpOmcTaskRedistribution/edit',
        queryById: '/api/erp/task/erpOmcTaskRedistribution/queryById',
        erpOmcProjectQueryById: '/api/erp/omc/project/erpOmcProject/queryById',
        queryPageList: '/api/erp/omc/project/erpOmcProjectTaskFinal/queryPageList',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      loading: false,
      memberColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '业务分类',
          align: 'center',
          dataIndex: 'categoryName',
          width: 240,
          ellipsis: true
        },
        {
          title: '合同占比(%)',
          align: 'center',
          dataIndex: 'contractRate',
          width: 120,
          ellipsis: true
        },
        {
          title: '合同分配额(元)',
          align: 'center',
          dataIndex: 'contractAmount',
          width: 130,
          ellipsis: true
        },
        {
          title: '切割合同额(元)',
          align: 'center',
          dataIndex: 'cutContractAmount',
          width: 130,
          ellipsis: true
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'productTeam',
          width: 200,
          ellipsis: true,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['productTeam'], text + '')
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          // fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      // 进度列表
      templateColumns: [
        {
          title: '顺序',
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '节点名称',
          align: 'center',
          dataIndex: 'nodeName'
        },
        {
          title: '节点进度',
          align: 'center',
          dataIndex: 'nodeProgress',
          scopedSlots: { customRender: 'titleSlot' }
        }
      ],

      // 款项进度
      paymentProgressColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '款项名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'nodeName'
        },
        {
          title: '金额(元)',
          align: 'center',
          ellipsis: true,
          dataIndex: 'paymentMoney'
        },
        {
          title: '款项节点说明',
          align: 'center',
          ellipsis: true,
          dataIndex: 'nodeDesc'
        },
        // {
        //   title: '应收日期',
        //   align: 'center',
        //   ellipsis: true,
        //   dataIndex: 'collectionDate'
        // },
        {
          title: '是否关联任务',
          align: 'center',
          ellipsis: true,
          customRender: (text) => {
            if (text === '' || text === null || text === undefined) {
              return ''
            } else {
              return text == 0 ? '否' : '是'
            }
          },
          dataIndex: 'isRelatedTask'
        },
        {
          title: '是否关联进度',
          align: 'center',
          ellipsis: true,
          customRender: (text) => {
            if (text === '' || text === null || text === undefined) {
              return ''
            } else {
              return text == 0 ? '否' : '是'
            }
          },
          dataIndex: 'isRelatedTaskNode'
        },
        {
          title: '任务进度',
          align: 'center',
          ellipsis: true,
          dataIndex: 'taskNodeId_dictText'
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   align: 'center',
        //   fixed: 'right',
        //   width: 147,
        //   scopedSlots: {
        //     filterDropdown: 'filterDropdown',
        //     filterIcon: 'filterIcon',
        //     customRender: 'action'
        //   }
        // }
      ],
      dictOptions: {},
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0'
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },

  watch: {
    'model.redistributionDtList'(val) {
      if (!val) return

      function parse(num) {
        return Number(num) || 0
      }
      // 所有成员的预算工时之和
      this.model.expectWorkTime = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.contractAmount)).plus(total).toNumber())
      }, 0)

      // 所有成员的人工成本之和
      this.model.workCost = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.laborCost)).plus(total).toNumber())
      }, 0)
    },
    activeKey(key) {
      this.$forceUpdate()
    },
    taskId: {
      handler (val) {
        if (!val) {
          this.$set(this.model, 'taskId', null) // 任务编号
          // this.model.taskId = null
          return false
        }
        // this.$set(this.modelDefault, 'taskId', val) // 任务档案编号
        // this.add(val)
        this.$nextTick(() => {
          this.$set(this.model, 'handlerId', this.userInfo().empId) // 申请人
          this.$set(this.model, 'handlerDeptId', this.userInfo().deptId) // 申请人
        })
        this.$set(this.model, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
        this.$set(this.model, 'taskId', val) // 任务编号
        this.generatedFormNumber();
        this.getReceivablePaymentList(val, null, '1') // 获取需分配的款项信息
        // 获取任务编号
        if (val) {
          getAction(this.url.queryPageList, { id: val }).then((res) => {
            if (res.success) {
              var event = res.result.records[0]
              this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
              this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
              this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
              this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额(元)
              this.$set(this, 'originalContractAmount', event.contractAmount)
              this.$set(this, 'cutTheContractAmount', event.cutContractAmount)
              this.$set(this.model, 'taskType', '3') // 默认任务类型为其他
              this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
              this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
              this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类编码
              this.taskInfoObj = event
              this.getPaymentTaskList(event, event.id)
            }
          })
        }
        this.visible = true;
      },
      immediate: true
    },
    projectNameId: {
      handler (val) {
        if (!val) {
          return false
        }
        getAction(this.url.erpOmcProjectQueryById, { id: val }).then((res) => {
          if (res.success) {
            var event = res.result
            this.$set(this.model, 'projectName', event.projectName) // 项目名称
            this.$set(this.model, 'projectId', val) // 项目id
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
            this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
            this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
            this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
            this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
            this.$set(this.model, 'year', event.year) // 业绩归属年度
            this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
            this.$set(this.model, 'contacts', event.contacts) // 联系人
            this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
            this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
            this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
            this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
            this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
            this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
            this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
            this.$set(this.model, 'attachment', event.attachment || null) // 项目附件
            this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';
          }
        })
      },
      immediate: true
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单databw
    this.showFlowData();
    // 加载数据字典信息
    this.initDictConfig();
    this.customKey = 'memberColumns'
    this.memberColumnswidth = this.memberColumns.map(val => {
      return val.width
    })
  },
  methods: {
    changeVal(val) {
      this.$set(this.model, 'productCompanyId',val[0].belongCompanyId)
    },
    // 如果选择是，则需分配合同额自动变更为原始的合同分配额（元），合同分配额自动变为0
    handleChangeIsCancel(val) {
      var _this = this
      if (val == '1') {
        if (_this.receivablePaymentList && _this.receivablePaymentList.length > 0) {
          this.$confirm({
            title: '是否确定此选择?',
            content: '选择为是，会清除需分配款项信息中的关联任务，是否继续？',
            onOk () {
              _this.model.isCancel = val
              _this.$set(_this.model, 'separateContractAmount', _this.originalContractAmount)
              _this.$set(_this.model, 'needCutContractAmount', _this.cutTheContractAmount)
              _this.$set(_this.model, 'contractAmount', 0)
              _this.$set(_this.model, 'cutContractAmount', 0)
              _this.getPaymentTaskList(_this.taskInfoObj, _this.taskInfoObj.id)
              _this.handleChangeSeparateContractAmount('isCancel')
              // 当有需分配款项信息时，需要清空原有的任务
              // 对比款项中的任务,删除原有的任务
              _this.receivablePaymentList.forEach((item, index) => {
                if (item && item.shouldPayFlag != '1' && item.planTaskVoList && item.planTaskVoList.length > 0) {
                  item.planTaskVoList.forEach((item1, ind) => {
                    // if (item1.taskId.indexOf('-') !== -1) {
                    //   _this.receivablePaymentList[index].planTaskVoList.splice(ind, 1);
                    // }
                    // 循环遍历新增分配任务信息是否与任务中的taskId相互匹配，匹配不上删除任务信息
                    if (_this.model.redistributionDtList && _this.model.redistributionDtList.length > 0) {
                      _this.model.redistributionDtList.forEach((item2, ind2) => {
                        if (item1.taskId != item2.id) {
                          _this.receivablePaymentList[index].planTaskVoList.splice(ind, 1);
                        }
                      })
                    } else {
                      // 没有新增的任务信息，则删除所有的任务
                      _this.receivablePaymentList[index].planTaskVoList = [];
                    }
                  })
                }
              })
              _this.receivablePaymentList.map((value, index) => {
                _this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
                // 遍历planTaskList数组赋值给taskId_dictText
                _this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
              })
            },
            onCancel() {
              _this.model.isCancel = '0'
              _this.handleChangeSeparateContractAmount('isCancel')
            }
          });
        } else {
          _this.model.isCancel = val
          _this.$set(_this.model, 'separateContractAmount', _this.originalContractAmount)
          _this.$set(_this.model, 'needCutContractAmount', _this.cutTheContractAmount)
          _this.$set(_this.model, 'contractAmount', 0)
          _this.$set(_this.model, 'cutContractAmount', 0)
          _this.handleChangeSeparateContractAmount('isCancel')
        }
      } else {
        _this.model.isCancel = val
        if (_this.receivablePaymentList && _this.receivablePaymentList.length > 0) {
          _this.getPaymentTaskList(_this.taskInfoObj, _this.taskInfoObj.id)
        }
        _this.handleChangeSeparateContractAmount('isCancel')
      }
    },
    handleChangeSeparateContractAmount(arg) {
      // contractRate
      // 需分配合同额不可大于需分配任务中原始的合同分配额
      if (this.model.separateContractAmount > this.originalContractAmount) {
        this.model.separateContractAmount = this.originalContractAmount
      }
      // 需分配切割合同额不可大于需分配任务中原始的切割合同额
      if (this.model.needCutContractAmount > this.cutTheContractAmount) {
        this.model.needCutContractAmount = this.cutTheContractAmount
      }
      // 如果需分配合同额等于初始的合同分配额，则是否作废自动变为是    如果 需分配切割合同额等于初始的切割合同额，则是否作废自动变为是
      if (arg != 'isCancel') {
        if (this.model.separateContractAmount === this.originalContractAmount) {
          this.$set(this.model, 'isCancel', '1')
        }
        if (this.model.needCutContractAmount === this.cutTheContractAmount) {
          this.$set(this.model, 'isCancel', '1')
        }
      }
      if (this.originalContractAmount && !isNaN(this.model.separateContractAmount)) {
        this.$set(this.model, 'contractAmount', this.originalContractAmount - this.model.separateContractAmount)
        // this.$set(this.model, 'cutContractAmount', this.model.cutContractAmount - this.model.needCutContractAmount)
        // 输入数字后，合同分配额会自动减少对应的金额，且需分配任务的合同占比也相应变小。需分配合同额不可大于需分配任务中原始的合同分配额。
        if (this.model.estimatedContractAmount) {
          this.$set(this.model, 'contractRate', this.model.contractAmount / this.model.estimatedContractAmount * 100)
        }
      }
      if (this.cutTheContractAmount && !isNaN(this.model.needCutContractAmount)) {
        this.$set(this.model, 'cutContractAmount', this.cutTheContractAmount - this.model.needCutContractAmount)
      }
    },
    // 添加项目成员回调
    submitCallback(data) {
      let flag = true;
      for (let i = 0; i < this.model.redistributionDtList.length; i++) {
        if (this.model.redistributionDtList[i].id === data.id) {
          this.model.redistributionDtList.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.model.redistributionDtList.push(data);
      } else {
        // 当是编辑的时候，查看需分配款项信息中的数据是否有绑定此任务，如果绑定则替换成新数据
        if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
          this.receivablePaymentList.forEach((item, index) => {
            if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
              item.planTaskVoList.forEach((item1, ind) => {
                if (item1.taskId == data.id) {
                  let obj = {
                    ...item1,
                    categoryName: data.categoryName,
                    taskDesc: data.taskDescription,
                    productTeam: data.productTeam,
                    productTeamName: data.productTeam_dictText,
                    productCompanyId: data.productCompanyId,
                  }
                  // data.planId = item.planId
                  this.receivablePaymentList[index].planTaskVoList.splice(ind, 1, obj);
                }
              })
            }
          })
          this.receivablePaymentList.map((value, index) => {
            this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
            // 遍历planTaskList数组赋值给taskId_dictText
            this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
          })
        }
      }
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      this.$forceUpdate()
    },
    ...mapGetters(['userInfo']),
    // 获取单据编号
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'RWZFP', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'billNo', res.result)
        }
      })
    },

    // 选择项目名称
    async onChangeProjectName (item) {
      var event = await item.choseObj[0]
      this.taskInfoObj = { id: '' } // 数据置空
      this.receivablePaymentList = [] // 款项置空
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      if (!event) {
        this.$set(this.model, 'projectName', '') // 项目名称
        this.$set(this.model, 'bail', '') // 保证金
        this.$set(this.model, 'finalNo', '') // 项目编号
        this.$set(this.model, 'teamName', '') // 经营团队
        this.$set(this.model, 'undertaker', '') // 项目承接人
        this.$set(this.model, 'projectEstablishDate', '') // 立项日期
        this.$set(this.model, 'signUnit', '') // 签订单位
        this.$set(this.model, 'year', '') // 业绩归属年度
        this.$set(this.model, 'ownerUnit', '') // 业主单位
        this.$set(this.model, 'contacts', '') // 联系人
        this.$set(this.model, 'contactTel', '') // 联系方式
        this.$set(this.model, 'areaCode', '') // 项目所在地址
        this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
        this.$set(this.model, 'projectSource', '') // 项目来源
        this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
        this.$set(this.model, 'establishReason', '') // 立项事由及说明
        this.$set(this.model, 'attachment', '') // 项目附件

        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
        this.$set(this.model, 'taskId', '') // 任务编号
        this.progressNodeVoList = [] // 清空款项进度
        return false
      }
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
      this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';

      this.$set(this.model, 'categoryName', '') // 业务分类
      this.$set(this.model, 'contractRate', '') // 合同占比(%)
      this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

      this.$set(this.model, 'productTeam', '') // 生产团队
      this.$set(this.model, 'productCompanyId', '') // 生产公司
      this.$set(this.model, 'taskId', '') // 任务编号
      this.$set(this.model, 'separateContractAmount', '') // 需分配合同额(元)
      this.$set(this.model, 'needCutContractAmount', '') // 需切割合同额(元)
      this.$set(this.model, 'isCancel', '') // 是否作废
      this.originalContractAmount = ''
      this.cutTheContractAmount = ''
			this.model.redistributionDtList = [] // 置空
    },

    // 选择任务编号
    onTaskIdInput (item) {
      var event = item.choseObj[0]
      if (!event) {
        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)
        this.taskInfoObj = { id: '' } // 数据置空
        this.receivablePaymentList = [] // 款项置空
        this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
        return false
      }
      this.getReceivablePaymentList(this.model.taskId, null, '1') // 获取需分配的款项信息
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类编码
      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.$set(this.model, 'separateContractAmount', '') // 需分配合同额(元)
      this.$set(this.model, 'needCutContractAmount', '') // 需切割合同额(元)
      this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额(元)
      // this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.originalContractAmount = event.contractAmount // 合同分配额(元)
      this.cutTheContractAmount = event.cutContractAmount // 切割合同额(元)
      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
      this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
      this.taskInfoObj = event
      this.getPaymentTaskList(event, event.id)
    },

    // 选择实施部门
    onExecuteDepartInput (item) {
      if (!item[0].minister) {
        this.$set(this.model, 'minister', undefined)
        return false
      }
      // 赋值部门负责人
      getAction('/api/erpmng/sys/api/queryUsersByUsernames', { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map(value => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },

    // 选择进度模板
    getTemplateList(data, obj) {
      if (data && data.length) {
        data.map(value => {
          value.id = this.getRandomNum()
        })
      }
      // 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
      let isAddChildNode = obj.isAddChildNode;
      data.forEach((item, index) => {
        if (index === data.length - 1) {
          item.isAddChildNode = '0';
        } else {
          item.isAddChildNode = isAddChildNode;
        }
      });
      this.templateDataList = data;
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = (new Date()).valueOf();// 获取时间戳
      let txt = '1234567890';// 生成的随机机器码
      let len = 19;// 机器码有多少位
      let pwd = '';// 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length));// 循环机器码位数随机填充
      }
      return date + pwd
    },

    initDictConfig() {
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'productTeam', res.result)
        }
      })
      initDictOptions('ywfx_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'ywfl', res.result)
        }
      })
      initDictOptions('erp_employee_file,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectMember', res.result)
        }
      })
    },
    // 获取需分配款项信息中的款项关联任务信息
    getPaymentTaskList (event, id) {
      this.paymentTaskList = []
      if (this.model.isCancel != '1') {
        // 当是否作废为是时则往paymentTaskList中添加一条原始任务信息
        let arr = (this.model.redistributionDtList && this.model.redistributionDtList.length) ? JSON.parse(JSON.stringify(this.model.redistributionDtList)) : []
        if (id) {
          let obj = {
            id,
            categoryCode: event.categoryCode, // 任务分类编码
            categoryName: event.categoryName, // 任务分类名称
            contractRate: event.contractRate, // 合同占比
            contractAmount: event.contractAmount, // 合同分配额
            cutContractAmount: event.cutContractAmount, // 切割合同额
            productTeam: event.productTeam, // 生产团队
            productTeam_dictText: event.productTeam_dictText, // 生产团队
            productCompanyId: event.productCompanyId, // 生产公司
            teamLeader: event.teamLeader, // 生产团队
            teamLeader_dictText: event.teamLeader_dictText, // 生产团队
            taskDescription: event.taskDescription // 任务说明
          }
          arr.push(obj)
        }
        this.paymentTaskList = arr
      } else {
        this.paymentTaskList = (this.model.redistributionDtList && this.model.redistributionDtList.length) ? JSON.parse(JSON.stringify(this.model.redistributionDtList)) : []
      }
    },
    add() {
      this.$set(this.modelDefault, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
      this.$set(this.modelDefault, 'handlerId', this.userInfo().empId) // 申请人
      this.$set(this.modelDefault, 'handlerDeptId', this.userInfo().deptId) // 申请人
      this.$set(this.modelDefault, 'taskType', '3') // 默认任务类型为其他
      this.modelDefault.redistributionDtList = []
      this.templateDataList = [] // 置空
      this.progressNodeVoList = [] // 置空
      this.model.redistributionDtList = [] // 置空
      this.receivablePaymentList = [] // 需分配款项信息置空
      this.edit(this.modelDefault);
      // this.userName = this.userInfo().empName;// 申请人名称
      this.generatedFormNumber();
    },
    async edit(record) {
      await this.$refs.form.resetFields();
      this.model = await Object.assign({}, record);
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + record.ownerUnit + '\'';
      // 获取项目数据
      if (this.model.projectId) {
        getAction(this.url.erpOmcProjectQueryById, { id: this.model.projectId }).then((res) => {
          if (res.success) {
            var event = res.result
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
          }
        })
      }
      if (this.model.id) {
        this.getReceivablePaymentList(record.taskId, record.id, '2') // 获取需分配的款项信息
        this.memberLoading = true
        // 获取新增分配任务信息
        getAction('/api/erp/task/erpOmcTaskRedistributionDt/queryByMainId', { mainId: this.model.id })
        .then(response => {
          this.model.redistributionDtList = response.result || []
        }).finally(() => {
          this.memberLoading = false
        })
      }
      if (this.model && this.model.taskId) {
        getAction('/api/erp/omc/project/erpOmcProjectTask/queryById', { id: this.model.taskId }).then(res => {
          this.taskInfoObj = res.result
          this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
        })
      } else {
        this.taskInfoObj = { id: '' } // 数据置空
        this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      }
      // 编辑的时候需要计算一下原始分配合同额
      this.originalContractAmount = Number(Number(this.model.separateContractAmount) + Number(this.model.contractAmount)) || 0
      this.cutTheContractAmount = Number(Number(this.model.needCutContractAmount) + Number(this.model.cutContractAmount)) || 0
      this.visible = true;
      this[this.customKey].forEach((val, index) => {
        val.width = this[this.customKey + 'width'][index]
      })
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },
    // 判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
    handleJudgePayment() {
      var isTrue = true // true为通过，false为不通过
      var _this = this
      var text = ''
      if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
        // 判断是是否作废
        if (this.model.isCancel == '1') {
          // 判断新增任务是否有数据
          if (_this.model.redistributionDtList && _this.model.redistributionDtList.length > 0) {
            this.receivablePaymentList.forEach((item, index) => {
              if (item && item.shouldPayFlag != '1' && item.planTaskVoList && item.planTaskVoList.length > 0) {
                const array1 = item.planTaskVoList
                const array2 = _this.model.redistributionDtList
                const matches = array1.every(item1 =>
                  array2.some(item2 => item1.taskId == item2.id)
                );
                if (!matches) {
                  text = '当选择"是否作废"为"是"，"需分配款项信息中的款项关联任务"需绑定"新增分配任务信息"中的任务！'
                  isTrue = false
                }
              }
            })
          } else {
            // 没有新增的任务信息，则删除所有的任务
            text = '请新增分配任务信息！'
            isTrue = false
          }
        }
        this.receivablePaymentList.forEach((item, index) => {
          if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
            // 判断item1中的 paymentMoney之和是否等于item中的isAllowDistributionMoney
            const listTotal = item.planTaskVoList.reduce((total, item1) => {
              const paymentMoney = Number(item1.paymentMoney) || 0;
              const decimalContractRate = new Decimal(paymentMoney);
              return total.plus(decimalContractRate);
            }, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
            if (listTotal != item.isAllowDistributionMoney) {
              text = '需分配款项信息中，绑定的款项关联任务中，款项分配占比没有达到100%！'
              isTrue = false
            }
          } else {
            text = '剩余未生成应收需要分配给新任务！'
            isTrue = false // 没有任务时，不允许通过
          }
        })
      }
      if (!isTrue) {
        this.$message.warning(text)
      }
      return isTrue
    },
    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            // 若保存时，是否作废为是但需分配合同额不等于原始合同额，则无法保存并给出提示：作废需分配任务时，请将需分配任务的所有合同额全部分配出去
            if (that.model.isCancel === '1') {
              if (Number(that.model.separateContractAmount) !== Number(that.originalContractAmount)) {
                const text = '作废需分配任务时，请将需分配任务的所有合同额全部分配出去!'
                that.$message.warning(text);
                that.$emit('unButtonDisable');
                return Promise.reject(text)
              }
              if (Number(that.model.needCutContractAmount) !== Number(that.cutTheContractAmount)) {
                const text = '作废需分配任务时，请将需分配任务的所有切割合同额全部分配出去!'
                that.$message.warning(text);
                that.$emit('unButtonDisable');
                return Promise.reject(text)
              }
            } else {
              if (Number(that.model.separateContractAmount) === Number(that.originalContractAmount)) {
                const text = '需分配任务的所有合同额全部分配出去后，请作废该任务!'
                that.$message.warning(text);
                that.$emit('unButtonDisable');
                return Promise.reject(text)
              }
              // if (Number(that.model.needCutContractAmount) === Number(that.cutTheContractAmount)) {
              //   const text = '需分配任务的所有切割合同额全部分配出去后，请作废该任务!'
              //   that.$message.warning(text);
              //   that.$emit('unButtonDisable');
              //   return Promise.reject(text)
              // }
            }
            // 列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比
            const listTotal = that.model.redistributionDtList.reduce((total, item) => {
              const contractRate = Number(item.contractRate) || 0;
              const decimalContractRate = new Decimal(contractRate);
              return total.plus(decimalContractRate);
            }, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
            // 判断预计合同额是否为0，不为0则在校验
            if (that.model.estimatedContractAmount != '0' && that.model.estimatedContractAmount != null) {
              const compareTotal = Number(Number(that.model.separateContractAmount / that.model.estimatedContractAmount * 100).toFixed(2))
              if (listTotal !== compareTotal) {
                const text = `列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比！当前需分配合同额占预计合同额的百分比为${compareTotal}%`
                that.$message.warning(text);
                that.$emit('unButtonDisable');
                return Promise.reject(text)
              }
            }
            // 列表中所有新增分配任务的合同分配额之和应该等于需分配合同额
            const listTotal2 = that.model.redistributionDtList.reduce((total, item) => {
              return total + (Number(item.contractAmount) || 0)
            }, 0)
            if (listTotal2 !== Number(that.model.separateContractAmount)) {
              const text = '列表中所有新增分配任务的合同分配额之和应该等于需分配合同额!'
              that.$message.warning(text);
              that.$emit('unButtonDisable');
              return Promise.reject(text)
            }
            // 列表中所有新增分配任务的切割合同额之和应该等于需分配切割合同额
            const listTotal3 = that.model.redistributionDtList.reduce((total, item) => {
              return total + (Number(item.cutContractAmount) || 0)
            }, 0)
            if (listTotal3 !== Number(that.model.needCutContractAmount)) {
              const text = '列表中所有新增分配任务的切割合同额之和应该等于需分配切割合同额!'
              that.$message.warning(text);
              that.$emit('unButtonDisable');
              return Promise.reject(text)
            }
            // 这里判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
            if (!that.handleJudgePayment()) {
              const text = '请完善需分配款项信息'
              // that.$message.warning(text);
              that.$emit('unButtonDisable');
              return Promise.reject(text)
            }
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      this.$set(this.model, 'redistributionPlanVoList', this.receivablePaymentList)
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      let model = {};
      Object.assign(model, this.model)
      model.undertakerName = model.undertaker
      // model.progressNodeVoList = this.progressNodeVoList // 款项详情
      model.progressVoList = this.templateDataList // 任务进度
      httpAction(httpurl, model, method).then(async(res) => {
        if (res.success) {
          if(type !== 'draft'){
            const verifyId = method === 'put' ? this.model.id : res.result; // 关键修改
         const result = await getAction('/api/erp/task/erpOmcTaskRedistribution/verify',{id:verifyId},'get')
         if(!result.success) {
           that.$message.warning(result.message);
           that.$emit('dialogClose')
           return
         }
          }
          
         that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },

    // 点击打印
    onPrint () {
      // eslint-disable-next-line no-unused-vars
      let print = new Print({
        el: '#taskContent',
        popTitle: '任务委托详情 · 禾美环保',
        endCallback() {

        }
      })
    },
    // 任务委托信息新增
    handleMemberAdd() {
      this.$refs.memberList.add();
      this.$refs.memberList.title = '新增';
      this.$refs.memberList.disableSubmit = false;
    },
    // 任务委托信息编辑
    handleMemberEdit(record) {
      this.$refs.memberList.edit(record);
      this.$refs.memberList.title = '修改';
      this.$refs.memberList.disableSubmit = false;
    },
    // 任务委托信息删除
    handleMemberDelete(id) {
      let indexNum = this.model.redistributionDtList.findIndex((item) => {
        return item.id == id
      })
      if (indexNum !== -1) {
        // 判断receivablePaymentList中的任务是否有含该id值，含了就需要删除
        if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
          this.receivablePaymentList.forEach((item, index) => {
            if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
              item.planTaskVoList.forEach((item1, ind) => {
                if (item1.taskId == id) {
                  this.receivablePaymentList[index].planTaskVoList.splice(ind, 1);
                }
              })
            }
          })
          this.receivablePaymentList.map((value, index) => {
            this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
            // 遍历planTaskList数组赋值给taskId_dictText
            this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
          })
        }
        this.model.redistributionDtList.splice(indexNum, 1);
      }
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      this.$forceUpdate()
    },
    // 款项进度子表编辑
    handlerPaymentEdit(record) {
      this.$refs.paymentForm.edit(record);
      this.$refs.paymentForm.title = '编辑';
      this.$refs.paymentForm.disableSubmit = false;
    },
    memberModalFormOk(data) {
      // this.memberLoading = true;
      let flag = true;
      for (let i = 0; i < this.progressNodeVoList.length; i++) {
        if (this.progressNodeVoList[i].id == data.id) {
          this.progressNodeVoList.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.progressNodeVoList.push(data);
      }
      // this.memberLoading = false;
    },
    // 编辑需分配款项信息列表
    handlePaymentEdit (record) {
      this.$refs.paymentModal.edit(record);
      this.$refs.paymentModal.title = '编辑';
      this.$refs.paymentModal.disableSubmit = false;
    },
    handleDetail(record) {
      // 修改时将当前的值从remain中减去
      this.editRemain = record.je;
      this.$refs.paymentModal.edit(record);
      this.$refs.paymentModal.title = '查看';
      this.$refs.paymentModal.disableSubmit = true;
    }
  }
}
</script>
<style lang="less" scoped>
.print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
.icon{
  font-size: 45px;
}
</style>
<style>
  @import "../../../../../utils/print.css";
</style>
